package com.atguigu.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author luoyin
 * @Date 17:58 2022/7/22
 **/
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //类型强转
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        //判断是否已经登录账户
        Object existUser = request.getSession().getAttribute("existUser");
        if(null == existUser){
            try {
                response.sendRedirect(request.getContextPath()+"/user?method=toLoginPage");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        chain.doFilter(request,response);
    }
}
